import os
import glob
import base64

import json
import subprocess


json_0 = "./tvbox/0.json"
json_99 = "./tvbox/99.json"
jq = "./jq_x86"
json0826 = "./0826.json"
img_to_str = "./img_to_str"

# spider地址
spider = "https://gitee.com/asters1/source/raw/master/tvbox/jar/xo.jar"
# spider="https://wisteria.cf/https://raw.githubusercontent.com/gaotianliuyun/gao/master/jar/fan.txt"
# spider="https://wisteria.cf/https://raw.githubusercontent.com/asters1/gao/master/jar/fan.txt"
asters_jar = "https://wisteria.cf/https://raw.githubusercontent.com/asters1/source/master/tvbox/jar_test/custom_spider.jar"

# live地址
live = "https://raw.gitcode.com/asters1/source/raw/master/tvbox/live/0"
# live64="aHR0cHM6Ly9yYXcuZ2l0Y29kZS5jb20vYXN0ZXJzMS9zb3VyY2UvcmF3L21hc3Rlci90dmJveC9saXZlLzA="
live64 = base64.b64encode(live.encode("utf-8")).decode("utf-8")
# 0826地址
xoUrl = "http://www.xn--sss604efuw.com/tv/"
xoJar = ""
# 不需要的site
NoSites = [
    "神秘的哥哥",
    "获取",
    "盘",
    "搜",
    "抠抠",
    "小米",
    "更新",
    "玩偶哥哥",
    "公众号",
    "叨观荐影",
    "直播",
    "动漫",
    "球",
    "MV",
    "小说",
    "视频",
    "体育",
    "教学",
    "导航",
    "广告",
    "飞",
    "课堂",
    "少儿",
    "儿童",
    "🅱",
    "推送",
]

ResultJstr = (
    '''{

        "wallpaper": "https://wisteria.cf/https://raw.githubusercontent.com/asters1/source/master/paper/6.jpg",
        "spider": "'''
    + spider
    + """",
        "lives": [{"group": "redirect","channels": [{"name": "live","urls": ["proxy://do=live&type=txt&ext="""
    + live64
    + """"]}]}],
        "sites": [],
        "parses":[],
        "rules": []
        }
        """
)


def get_js_files(directory):
    # 切换到指定目录
    os.chdir(directory)
    # 使用glob模块查找所有以.js结尾的文件
    js_files = glob.glob("*.js")
    return js_files


# def get_all_files_in_directory(directory):
#     files = []
#     for file in os.listdir(directory):
#         if os.path.isfile(os.path.join(directory, file)):
#             files.append(file)
#             return files
#


def Init():
    print("Init")
    global jq
    global img_to_str
    uname = os.uname().machine
    if uname == "aarch64":
        jq = "./jq_termux"
        img_to_str = "./img_to_str_termux"
    os.system(img_to_str + " " + xoUrl + " " + json0826)

    os.system("cp " + json0826 + " ./tvbox/xo.json")
    spider_jar = subprocess.run(
        jq + " -fG " + json0826 + " spider ",
        stdout=subprocess.PIPE,
        shell=True,
    ).stdout.decode("utf-8")
    # print(spider_jar)
    xoJar = spider_jar.split(";")[0]
    # print(xoJar)

    os.system("curl -so fan.txt " + xoJar)
    os.system("mv fan.txt ./tvbox/jar/xo.jar")
    # print(uame)
    # print(uame)
    W(json_0, ResultJstr)
    W(json_99, ResultJstr)


def W(path, content):
    if not os.path.exists(os.path.dirname(path)):
        os.makedirs(os.path.dirname(path))
    with open(path, "w", encoding="utf-8") as f:
        f.write(content)


def R(path):
    with open(path, "r", encoding="utf-8") as f:
        content = f.read()
        return content


def sites():
    jstr = R(json0826)
    # print(jq)
    res = subprocess.run(
        jq + " -fG " + json0826 + " sites ",
        stdout=subprocess.PIPE,
        shell=True,
    ).stdout.decode("utf-8")
    xo_json = subprocess.run(
        jq
        + " -fS "
        + json0826
        + ' spider "\\"https:wisteria.cf/https://raw.githubusercontent.com/asters1/gao/master/jar/fan.txt\\"" ',
        stdout=subprocess.PIPE,
        shell=True,
    ).stdout.decode("utf-8")
    res = res.strip()[1:-1].strip()

    res_list = res.split("\n")
    # print(res_list)
    insert_0 = (
        '''[
        {"key": "ikanbot","name": "🕸️蜘蛛┃SP","type": 3,"api": "csp_IkanBot","playerType": 1,"searchable": 1,"quickSearch": 1,"filterable": 1,"jar":"'''
        + asters_jar
        + """"},
{"key": "zj5","name": "🏍️追剧┃JS","type": 3,"api": "https://gitee.com/asters1/source/raw/master/drpy_js/drpy2.min.js","playerType": 1,"searchable": 1,"quickSearch": 1,"filterable": 1,"ext":"https://gitee.com/asters1/source/raw/master/drpy_js/zj5.js"},
        """
    )
    # {"key": "ikanbot","name": "🕸️蜘蛛┃SP","type": 3,"api": "https://gitee.com/asters1/source/raw/master/drpy_js/drpy2.min.js","playerType": 1,"searchable": 1,"quickSearch": 1,"filterable": 1,"ext":"https://gitee.com/asters1/source/raw/master/drpy_js/%E7%88%B1%E7%9C%8B%E6%9C%BA%E5%99%A8%E4%BA%BA%5B%E8%99%AB%5D.js"},"""
    insert_99 = (
        '''[
        {"key": "ikanbot","name": "🕸️蜘蛛┃SP","type": 3,"api": "csp_IkanBot","playerType": 1,"searchable": 1,"quickSearch": 1,"filterable": 1,"jar":"'''
        + asters_jar
        + """"},
{"key": "zj5","name": "🏍️追剧┃JS","type": 3,"api": "https://gitee.com/asters1/source/raw/master/drpy_js/drpy2.min.js","playerType": 1,"searchable": 1,"quickSearch": 1,"filterable": 1,"ext":"https://gitee.com/asters1/source/raw/master/drpy_js/zj5.js"},
        """
    )
    # print(res_list)
    result = ""
    for item in res_list:
        for Nsite in NoSites:
            if Nsite in item:
                # print(Nsite)
                item = ""
        if item != "":
            result += item + "\n"
            # print(item)
    # print(result)
    Sres0 = subprocess.run(
        jq + " -fS " + json_0 + " sites '" + insert_0 + result + PNull(60) + "'",
        stdout=subprocess.PIPE,
        shell=True,
    ).stdout.decode("utf-8")
    Sres99 = subprocess.run(
        jq + " -fS " + json_99 + " sites '" + insert_99 + result + PNull(60) + "'",
        stdout=subprocess.PIPE,
        shell=True,
    ).stdout.decode("utf-8")
    W(json_0, Sres0)
    W(json_99, Sres99)
    W(json0826, xo_json)


def PNull(num):
    result = ""
    for i in range(0, num):
        a = (
            '''
{"key": "'''
            + str(i)
            + """","name": "","type": 3,"api": "","playerType": 1,"searchable": 1,"quickSearch": 1,"filterable": 1},"""
        )
        result += a
    result += """{"key": "end","name": "","type": 3,"api": "","playerType": 1,"searchable": 1,"quickSearch": 1,"filterable": 1}
    ]"""
    return result


def rules():
    print("rules")
    # res=subprocess.run(jq+" -fG "+json0826+" rules ",stdout=subprocess.PIPE,shell=True,).stdout.decode("utf-8")
    # result=subprocess.run(jq+" -fS "+json_0+" rules '"+res+"'",stdout=subprocess.PIPE,shell=True,).stdout.decode("utf-8")
    # print(result)
    # W(json_0,result)
    # W(json_99,result)

    # print(res)


def parses():
    print("parses")


def End():
    # os.system("mv " + json0826 + " ./tvbox/xo.json")
    print()


def DrpyJs():
    js_list_all = get_js_files("./drpy_js/")
    js_list = [file for file in js_list_all if file != "drpy2.min.js"]

    # print(js_list)
    js_json = {}
    js_json["wallpaper"] = (
        "https://wisteria.cf/https://raw.githubusercontent.com/asters1/source/master/paper/6.jpg"
    )
    sites = []
    for f_name in js_list:
        json_file = {}
        json_file["key"] = f_name[:-3]
        json_file["name"] = f_name[:-3]
        json_file["type"] = 3
        json_file["api"] = "https://gitlab.com/fantaiying/ext/-/raw/main/drpy2.min.js"
        json_file["playerType"] = 1
        json_file["searchable"] = 1
        json_file["quickSearch"] = 1
        json_file["changeable"] = 1
        json_file["ext"] = (
            "https://gitee.com/asters1/source/raw/master/drpy_js/" + f_name
        )

        sites.append(json_file)

    # print(sites)
    js_json["sites"] = sites
    js_json["parses"] = []
    js_json["rules"] = []

    W("./drpy.json", json.dumps(js_json))
    # W("a.json", "kk")


if __name__ == "__main__":
    # PNull(10)
    Init()
    rules()
    parses()
    # print("====")
    sites()

    DrpyJs()
    End()
